<template>
  <a-form class="send-msg" ref="formRef" :model="formData" :label-col="labelCol" :wrapper-col="wrapperCol">
    <a-form-item name="isSend" :label-col="{ span: 0 }" :wrapper-col="{ span: 21, offset: 3 }">
      <a-checkbox v-model:checked="isSend">是否需要发送短信提醒</a-checkbox>
    </a-form-item>
    <a-form-item
      v-if="isSend"
      name="content"
      label="短信内容"
      extra="请勿输入涉密内容！！！"
      :rules="{ required: isSend === true, message: '请输入短信内容' }"
      class="send-msg-content"
      style="margin-bottom: 42px"
    >
      <a-textarea
        v-model:value="formData.content"
        :rows="2"
        :maxlength="300"
        :show-count="true"
        placeholder="请输入短信内容"
      ></a-textarea>
    </a-form-item>
    <a-form-item
      v-if="isSend"
      name="phone"
      label="短信接收号码"
      extra="多个电话号码请使用逗号隔开"
      :rules="[
        { required: isSend === true, message: '请输入短信接收号码' },
        { validator: validatePhone, trigger: 'blur' },
      ]"
    >
      <a-textarea
        v-model:value="formData.phone"
        :rows="2"
        placeholder="请输入短信接收号码,多个电话号码请使用逗号隔开"
      ></a-textarea>
    </a-form-item>
  </a-form>
</template>

<script>
import { sendMsgByPhone } from '@gis/lib/api';
import { validateForm } from '@gis/lib/components/antd-form/form.js';
import { handleFormResult } from '@gis/lib/utils/resolver.js';

export default {
  name: 'send-msg',
  props: {
    labelCol: { type: Object, default: () => ({ span: 3 }) },
    wrapperCol: { type: Object, default: () => ({ span: 21 }) },
    content: { type: String, default: '' },
    phone: { type: String, default: '' },
  },
  data() {
    return {
      isSend: 0,
      formData: {
        content: '',
        phone: '',
      },
    };
  },
  created() {
    this.formData = { ...this.formData, content: this.content, phone: this.phone };
  },
  methods: {
    splitter(value) {
      return typeof value === 'string' ? value.split(/[,，]+/).filter(Boolean) : [];
    },
    async validatePhone(rule, value) {
      value = this.splitter(value);
      if (!value.length) {
        return Promise.reject('请输入电话号码');
      }
      for (const index in value) {
        if (!/^1[3456789]\d{9}$/.test(value[index])) {
          const num = index - 0 + 1;
          return Promise.reject('请正确输入电话号码,第' + num + '个电话号码应该为11位');
        }
      }
      return Promise.resolve();
    },
    async send() {
      if (this.isSend !== true) {
        return true;
      }
      // const ok = await this.$refs.formRef.validate();
      const ok = await validateForm(this.$refs.formRef);
      if (!ok) {
        return false;
      }
      let { content, phone } = this.formData;
      phone = this.splitter(phone).join(',');
      return handleFormResult(await sendMsgByPhone({ phone, content }).catch(() => {}), {
        baseText: '发送短信',
      });
    },
  },
};
</script>

<style lang="less">
.send-msg {
  .send-msg-content {
    .ant-form-item-extra {
      color: #f5222d;
    }
  }
}
</style>
